package it.infodea.tapestrydea.mixins.jswindows;

import it.infodea.tapestrydea.services.jwindows.JsWindowsThemesAssetsProvider;

import org.apache.tapestry5.Asset;
import org.apache.tapestry5.BindingConstants;
import org.apache.tapestry5.MarkupWriter;
import org.apache.tapestry5.RenderSupport;
import org.apache.tapestry5.annotations.AfterRender;
import org.apache.tapestry5.annotations.IncludeJavaScriptLibrary;
import org.apache.tapestry5.annotations.IncludeStylesheet;
import org.apache.tapestry5.annotations.InjectContainer;
import org.apache.tapestry5.annotations.Parameter;
import org.apache.tapestry5.corelib.base.AbstractLink;
import org.apache.tapestry5.dom.Element;
import org.apache.tapestry5.ioc.annotations.Inject;

@IncludeJavaScriptLibrary({"classpath:/it/infodea/tapestrydea/assets/scripts/jswindows/window.js", "classpath:/it/infodea/tapestrydea/assets/scripts/jswindows/window_effects.js", "PreviewContentWindow.js"})
@IncludeStylesheet({"classpath:/it/infodea/tapestrydea/assets/scripts/jswindows/themes/default.css"})
public class PreviewContentWindow {
	
	private static final String JS_FORMAT_STRING = "PreviewContentWindow.registerButton('%s', '%s', '%s', '%s');";

	@Parameter(defaultPrefix=BindingConstants.LITERAL, value="Preview Content Window")
	private String windowTitle;
	
	@Parameter(defaultPrefix=BindingConstants.LITERAL, value="bluelighting")
	private String windowTheme;
	
	@Inject
	private RenderSupport renderSupport;
	
	@Inject
	private JsWindowsThemesAssetsProvider themesAssetsProvider;
	
	@InjectContainer
	private AbstractLink link;
	
	@AfterRender
	void afterRender(MarkupWriter writer){
		String clientId = link.getClientId();
		String linkUrl = link.getLink().toRedirectURI();
		Element elementById = writer.getDocument().getElementById(clientId);
		elementById.forceAttributes("href", "javascript:");
		Asset[] assets = themesAssetsProvider.provideAssets(windowTheme);
		if(assets != null){
			for (Asset asset : assets) {
				renderSupport.addStylesheetLink(asset, null);
			}
		}
		renderSupport.addScript(JS_FORMAT_STRING, 
				clientId, linkUrl, windowTitle, windowTheme);
	}

}
